<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="商户">
            <el-select
              v-model="searchForm.MerchantId"
              placeholder="请选择商户"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上游平台配置">
            <el-select
              v-model="searchForm.UpstreamPlatformId"
              placeholder="请选择上游平台配置"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in upstreamPlatformOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 商户表格 -->
      <el-table 
        :data="userList" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="Id" label="id" width="80"/>
        <el-table-column prop="Merchant" label="商户邮箱" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Email }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Merchant" label="商户名称" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Name }}</span>
          </template>
        </el-table-column><el-table-column prop="UpstreamPlatform" label="上游平台名称" width="120">
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpstreamPlatform" label="上游平台代码" width="120">
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.Code }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ClientId" label="上游平台clientId" width="200">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.ClientId" placement="top">
                <span class="text-ellipsis">{{ scope.row.ClientId }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.ClientId, 'ClientId')"
                class="copy-btn"
                v-if="scope.row.ClientId"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="ApiKey" label="上游平台api密钥" width="200">
          <template #default="scope">
            <div class="copy-cell">
              <el-tooltip :content="scope.row.ApiKey" placement="top">
                <span class="text-ellipsis">{{ scope.row.ApiKey }}</span>
              </el-tooltip>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.ApiKey, 'ApiKey')"
                class="copy-btn"
                v-if="scope.row.ApiKey"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column> 
        <el-table-column prop="UpstreamPlatform" label="请求基础地址" show-overflow-tooltip width="120">
          <template #default="scope">
            <span>{{ scope.row.UpstreamPlatform?.BaseUrl }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">更新</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/更新商户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="ClientId" prop="ClientId">
          <el-input v-model="userForm.ClientId" placeholder="请输入ClientId" />
        </el-form-item>
        <el-form-item label="ApiKey" prop="ApiKey">
          <el-input v-model="userForm.ApiKey" placeholder="请输入ApiKey" />
        </el-form-item>
        <!-- <el-form-item label="ApiSecret" prop="ApiSecret">
          <el-input v-model="userForm.ApiSecret" placeholder="请输入ApiSecret" />
        </el-form-item> -->
        <el-form-item label="商户" prop="MerchantId" v-if="dialogType === 'add'">
          <el-select
            v-model="userForm.MerchantId"
            placeholder="请选择商户"
            clearable
          >
            <el-option
              v-for="item in merchantIdOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上游平台配置" prop="UpstreamPlatformId" v-if="dialogType === 'add'">
          <el-select
            v-model="userForm.UpstreamPlatformId"
            placeholder="请选择上游平台配置"
            clearable
          >
            <el-option
              v-for="item in upstreamPlatformOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import { upstreamPlatFormConfigList, createUpstreamConfig, updateUpstreamConfig, deleteUpstreamConfig } from '@/api/merchant'
import { upstreamPlatformList, merchantList } from '@/api/selectList'

// 响应式数据
const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const userFormRef = ref()
const merchantIdOptions = ref([])
const upstreamPlatformOptions = ref([])

// 搜索表单
const searchForm = reactive({
  MerchantId: null,
  UpstreamPlatformId: null
})

// 商户表单
const userForm = reactive({
  Id: '',
  ApiKey: '',
  // ApiSecret: '',
  ClientId: null,
  MerchantId: null,
  UpstreamPlatformId: null
})

// 表单验证规则
const userRules = {
  ApiKey: [
    { required: true, message: '请输ApiKey', trigger: 'blur' },
  ],
  // ApiSecret: [
  //   { required: true, message: '请输入ApiSecret', trigger: 'blur' }
  // ],
  ClientId: [
    { required: true, message: '请输入ClientId', trigger: 'blur' }
  ],
  MerchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  UpstreamPlatformId: [
    { required: true, message: '请选择上游平台配置', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增商户上游平台配置' : '更新商户上游平台配置'
})

// 获取商户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await upstreamPlatFormConfigList({
      Page: currentPage.value,
      PageSize: pageSize.value,
      ...searchForm
    })
    if (res.code === 200) {
      userList.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取商户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    MerchantId: null,
    UpstreamPlatformId: null
  })
  currentPage.value = 1
  getUserList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getUserList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getUserList()
}

// 新增商户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑商户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 深拷贝数据，避免直接修改
  Object.assign(userForm, JSON.parse(JSON.stringify(row)))
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除该商户上游平台配置吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await deleteUpstreamConfig({ UpstreamConfigId: row.Id })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getUserList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    if (dialogType.value === 'add') {
      // 新增商户
      const newUser = {
        ApiKey: userForm.ApiKey,
        // ApiSecret: userForm.ApiSecret,
        ClientId: userForm.ClientId,
        MerchantId: userForm.MerchantId,
        UpstreamPlatformId: userForm.UpstreamPlatformId,
      }
      const res = await createUpstreamConfig(newUser)
      if (res.code === 200) {
        ElMessage.success('新增商户上游平台配置成功')
      } else {
        ElMessage.error(res.message)
      }
    } else {
      // 编辑商户
      const newUser = {
        UpstreamConfigId: userForm.Id,
        ApiKey: userForm.ApiKey,
        // ApiSecret: userForm.ApiSecret,
        ClientId: userForm.ClientId,
        // MerchantId: userForm.MerchantId,
        // UpstreamPlatformId: userForm.UpstreamPlatformId,
      }
      const res = await updateUpstreamConfig(newUser)
      if (res.code === 200) {
        ElMessage.success('更新商户上游平台配置成功')
      } else {
        ElMessage.error(res.message)
      }
    }    
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    Id: '',
    ApiKey: '',
    // ApiSecret: '',
    ClientId: null,
    MerchantId: null,
    UpstreamPlatformId: null
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 复制功能
const handleCopy = async (text, fieldName) => {
  try {
    if (!text) {
      ElMessage.warning('复制内容为空')
      return
    }
    
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      ElMessage.success(`${fieldName}复制成功`)
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          ElMessage.success(`${fieldName}复制成功`)
        } else {
          ElMessage.error('复制失败')
        }
      } catch (err) {
        ElMessage.error('复制失败')
      }
      
      document.body.removeChild(textArea)
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

const getUpstreamPlatformOptions = async () => {
  try {
    const res = await upstreamPlatformList()
    if (res.code === 200) {      
      upstreamPlatformOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 生命周期
onMounted(() => {
  getUserList()
  getMerchantIdOptions()
  getUpstreamPlatformOptions()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 复制按钮样式 */
.copy-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-ellipsis {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px;
  margin: 0;
}

.copy-btn:hover {
  color: var(--el-color-primary);
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>